package com.nf.health.app.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LayoutAnimationController;
import android.view.animation.TranslateAnimation;
import android.widget.ListView;

import com.nf.health.app.MyApplication;
import com.nf.health.app.R;
import com.nf.health.app.activity.my.MyShopStoreActivity;
import com.nf.health.app.http.Apis;
import com.nf.health.app.widget.DialogFactory;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 工具类
 */
public class Util {
    public static String toHexStr(int i) {
        String str = Integer.toHexString(i);
        if (str.length() == 1) {
            str = "0" + str;
        }
        return str;
    }


    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    /**
     * Convert char to byte
     *
     * @param c char
     * @return byte
     */
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    public static String toStringHex(String s) {
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "utf-8");// UTF-16le:Not
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }

    private static final double EARTH_RADIUS = 6378137;

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * 登录密码加密
     *
     * @param code
     * @return
     */
    public static String encode(String code) {
        if (TextUtils.isEmpty(code)) {
            return "";
        }
        StringBuffer rs = new StringBuffer("");
        for (int i = 0; i < code.length(); i++) {
            rs.append("$").append((int) code.charAt(i)).append("1").append(";");
        }
        return new String(rs);
    }

    /**
     * 匹配包括下划线的任何单词字符。类似但不等价于“[A-Za-z0-9_]”
     *
     * @param phoneNumber
     * @return
     */
    public static boolean isPassword(String phoneNumber) {
        Pattern p = Pattern.compile("^[\\w.]{6,20}$");
        Matcher m = p.matcher(phoneNumber);
        return m.matches();
    }

    /**
     * 是否是手机号
     *
     * @param phoneNumber
     * @return
     */
    public static boolean isPhone(String phoneNumber) {
        Pattern p = Pattern.compile("^[1][2-9]\\d{9}");
        Matcher m = p.matcher(phoneNumber);
        return m.matches();
    }

    /**
     * 是否是昵称
     *
     * @return
     */
    public static boolean isNick(String value) {
        Pattern p = Pattern.compile("^[\u4e00-\u9fa5a-zA-Z0-9_]+$");
        Matcher m = p.matcher(value);
        return m.matches();
    }

    /**
     * 匹配是否是中文
     *
     * @return
     */
    public static boolean isChinese(String chinese) {
        Pattern p = Pattern.compile("[\u4E00-\u9FFF]{2,10}");
        Matcher m = p.matcher(chinese);
        return m.matches();
    }

    /**
     * 判断是否是数值
     *
     * @param s
     * @return
     */
    public static boolean isNum(String s) {
        Pattern p = Pattern.compile("^\\d+\\.?\\d+$");
        Matcher m = p.matcher(s);
        return m.matches();
    }

    /**
     * 是否是空
     *
     * @param str
     * @return
     */
    public static Boolean isNull(String str) {
        String regStartSpace = "^[　 ]*";
        String regEndSpace = "[　 ]*$";
        String strDelSpace = str.replaceAll(regStartSpace, "").replaceAll(
                regEndSpace, "");
        return strDelSpace.length() == 0;
    }

    /**
     * 匹配分行信息 1-10 汉字
     *
     * @param str
     * @return
     */
    public static Boolean isBranchBank(String str) {
        Pattern p = Pattern.compile("[\u4E00-\u9FA5]{1,10}");
        Matcher m = p.matcher(str);
        return m.matches();

    }

    public static boolean isQQ(String QQNumber) {
        Pattern p = Pattern.compile("^[1-9]\\d{4,9}$");
        Matcher m = p.matcher(QQNumber);
        return m.matches();
    }

    /**
     * 6到10位的数字组合
     *
     * @param password
     * @return
     */
    public static boolean isPassword2(String password) {
        Pattern p = Pattern.compile("[0-9]{6,10}");
        Matcher m = p.matcher(password);
        return m.matches();
    }

    private static final String ID_CARD_PATTERN = "[0-9]{6}(1[9]|2[0])\\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])\\d{3}(\\d|\\w)";

    public static boolean isIDCARD(String ID) {
        Pattern p = Pattern.compile(ID_CARD_PATTERN);
        Matcher m = p.matcher(ID);
        return m.matches();
    }

    public static String getDate() {
        SimpleDateFormat ft = new SimpleDateFormat("yyyy/MM/dd");
        Date dd = new Date();
        return ft.format(dd);
    }

    public static long getQuot(String time1, String time2) {
        long quot = 0;
        SimpleDateFormat ft = new SimpleDateFormat("yyyy/MM/dd");
        try {
            Date date1 = ft.parse(time1);
            Date date2 = ft.parse(time2);
            quot = date1.getTime() - date2.getTime();
            quot = quot / 1000 / 60 / 60 / 24;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return quot;
    }

    /**
     * 图片加载优化
     *
     * @param options
     * @param minSideLength
     * @param maxNumOfPixels
     * @return
     */
    public static int computeInitialSampleSize(BitmapFactory.Options options,
                                               int minSideLength, int maxNumOfPixels) {
        double w = options.outWidth;
        double h = options.outHeight;

        int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
                .sqrt(w * h / maxNumOfPixels));
        int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(
                Math.floor(w / minSideLength), Math.floor(h / minSideLength));

        if (upperBound < lowerBound) {
            // return the larger one when there is no overlapping zone.
            return lowerBound;
        }

        if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
            return 1;
        } else if (minSideLength == -1) {
            return lowerBound;
        } else {
            return upperBound;
        }
    }

    /**
     * 微信唯一标识
     *
     * @param type
     * @return
     */
    public static String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis())
                : type + System.currentTimeMillis();
    }

    /**
     * 转换图片成圆形
     *
     * @param bitmap 传入Bitmap对象
     * @return
     */
    public static Bitmap toRoundBitmap(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float roundPx;
        float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
        if (width <= height) {
            roundPx = width / 2;
            top = 0;
            bottom = width;
            left = 0;
            right = width;
            height = width;
            dst_left = 0;
            dst_top = 0;
            dst_right = width;
            dst_bottom = width;
        } else {
            roundPx = height / 2;
            float clip = (width - height) / 2;
            left = clip;
            right = width - clip;
            top = 0;
            bottom = height;
            width = height;
            dst_left = 0;
            dst_top = 0;
            dst_right = height;
            dst_bottom = height;
        }

        Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect src = new Rect((int) left, (int) top, (int) right,
                (int) bottom);
        final Rect dst = new Rect((int) dst_left, (int) dst_top,
                (int) dst_right, (int) dst_bottom);
        final RectF rectF = new RectF(dst);
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, src, dst, paint);
        return output;
    }

    /**
     * 图片转为灰色
     *
     * @param bmSrc
     * @return
     */
    public static Bitmap bitmap2Gray(Bitmap bmSrc) {
        int width, height;
        height = bmSrc.getHeight();
        width = bmSrc.getWidth();
        Bitmap bmpGray = null;
        bmpGray = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        Canvas c = new Canvas(bmpGray);
        Paint paint = new Paint();
        ColorMatrix cm = new ColorMatrix();
        cm.setSaturation(0);
        ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
        paint.setColorFilter(f);
        c.drawBitmap(bmSrc, 0, 0, paint);

        return bmpGray;
    }

    /**
     * 去除所有空格制表符 换行
     *
     * @param str
     * @return
     */
    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    /**
     * 圆角矩形
     * <p/>
     * 图像的宽度
     * 图像的高度
     *
     * @param image 源图片
     *              圆角的大小
     * @return 圆角图片
     */
    public static Bitmap createFramedPhoto(Bitmap image, int rat) {
        int x = image.getWidth();
        int y = image.getHeight();
        float outerRadiusRat;
        if (rat == 0)
            outerRadiusRat = 20;
        else
            outerRadiusRat = rat;

        // 根据源文件新建一个darwable对象
        Drawable imageDrawable = new BitmapDrawable(image);

        // 新建一个新的输出图片
        Bitmap output = Bitmap.createBitmap(x, y, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        // 新建一个矩形
        RectF outerRect = new RectF(0, 0, x, y);

        // 产生一个红色的圆角矩形
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.RED);
        canvas.drawRoundRect(outerRect, outerRadiusRat, outerRadiusRat, paint);

        // 将源图片绘制到这个圆角矩形上
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        imageDrawable.setBounds(0, 0, x, y);
        canvas.saveLayer(outerRect, paint, Canvas.ALL_SAVE_FLAG);
        imageDrawable.draw(canvas);
        canvas.restore();

        return output;
    }

    /**
     * 获取屏幕的宽度
     */
    public final static int getWindowsWidth(Activity activity) {
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }

    /***
     * 计算百分比
     *
     * @param y
     * @param z
     * @return
     */
    public static double myPercent(double y, double z) {
        String baifenbi = "";// 接受百分比的值
        String baifenbiTemp = "";// 接受百分比的值
        double baiy = y * 1.0;
        double baiz = z * 1.0;
        double fen = baiy / baiz;
        NumberFormat nf = NumberFormat.getPercentInstance(); // 注释掉的也是一种方法
        nf.setMinimumFractionDigits(2); // 保留到小数点后几位
        DecimalFormat df1 = new DecimalFormat("##%"); // ##.00%
        // 百分比格式，后面不足2位的用0补齐
        baifenbiTemp = nf.format(fen);

        baifenbi = df1.format(fen);
        double temp = 0;
        try {
            temp = Double.parseDouble(baifenbi.replace("%", "").trim());
        } catch (Exception e) {
            // TODO: handle exception
            temp = 0;
        }
        return temp;
    }

    /***
     * 计算百分比小数点后两位
     *
     * @param y
     * @param z
     * @return
     */
    public static String myPercentDecimal(double y, double z) {
        String baifenbi = "";// 接受百分比的值
        String baifenbiTemp = "";// 接受百分比的值
        double baiy = y * 1.0;
        double baiz = z * 1.0;
        double fen = baiy / baiz;
        NumberFormat nf = NumberFormat.getPercentInstance(); // 注释掉的也是一种方法
        nf.setMinimumFractionDigits(2); // 保留到小数点后几位
        DecimalFormat df1 = new DecimalFormat("##%"); // ##.00%
        // 百分比格式，后面不足2位的用0补齐
        baifenbiTemp = nf.format(fen);

        return baifenbiTemp;
    }

    /***
     * 计算百分比
     *
     * @param y
     * @param z
     * @return
     */
    public static String myPercentDecimalTwo(double y, double z) {
        String baifenbi = "";// 接受百分比的值
        String baifenbiTemp = "";// 接受百分比的值
        double baiy = y * 1.0;
        double baiz = z * 1.0;
        double fen = baiy / baiz;
        NumberFormat nf = NumberFormat.getPercentInstance(); // 注释掉的也是一种方法
        nf.setMinimumFractionDigits(2); // 保留到小数点后几位
        DecimalFormat df1 = new DecimalFormat("##%"); // ##.00%
        // 百分比格式，后面不足2位的用0补齐
        baifenbiTemp = nf.format(fen);

        return baifenbiTemp;
    }

    /***
     * 保留两位小数
     * num ,String类型的数字
     *
     * @return
     */
    public static String saveDecimalTwo(double num) {
        String baifenbiTemp = "";
        DecimalFormat df1 = new DecimalFormat("0.00");
        baifenbiTemp = df1.format(num);
        return baifenbiTemp;
    }

    public static BitmapFactory.Options options;


    /**
     * 计算剩余时间 小时天
     *
     * @param time
     * @return
     */
    public static String getQuot(long time) {
        long dd = 0;
        long hh = 0;
        long mm = 0;
        long ss = 0;
        dd = time / 1000 / (60 * 60 * 24);
        hh = time / 1000 / (60 * 60);
        mm = time / 1000 / 60;
        ss = time / 1000;
        if (dd != 0) {
            return dd + "天";
        } else if (hh != 0) {
            return hh + "小时";
        } else if (mm != 0) {
            return mm + "分钟";
        } else if (ss != 0) {
            return 1 + "分钟";
        }
        String strTime = dd + "天" + hh + "时" + mm + "分" + ss + "秒";
        return strTime;

    }

    /**
     * 计算剩余时间 小时
     *
     * @param time
     * @return
     */
    public static String getHour(long time) {
        long dd = 0;
        long hh = 0;
        long mm = 0;
        long ss = 0;
        // dd = time / 1000 / (60 * 60 * 24);
        hh = time / 1000 / (60 * 60);
        mm = time / 1000 / 60;
        ss = time / 1000;
        if (dd != 0) {
            return dd + "天";
        } else if (hh != 0) {
            return hh + "小时";
        } else if (mm != 0) {
            return mm + "分钟";
        } else if (ss != 0) {
            return 1 + "分钟";
        }
        String strTime = dd + "天" + hh + "时" + mm + "分" + ss + "秒";
        return strTime;

    }

    // 四舍五入
    public static int StringToRounding(String value) {
        // BigDecimal temp = null;
        // try {
        // temp = new BigDecimal(value + "").setScale(0,
        // BigDecimal.ROUND_HALF_UP);
        // } catch (Exception e) {
        // temp = temp = new BigDecimal("1").setScale(0,
        // BigDecimal.ROUND_HALF_UP);
        // }

        Double temp1 = 0.0;
        int temp2 = 0;
        try {
            temp1 = Double.parseDouble(value);
            temp2 = (int) Math.ceil(temp1);
        } catch (Exception e) {
            // TODO: handle exception
        }

        return temp2;
    }

    /**
     * 加0
     *
     * @param temp
     * @return
     */
    public static String addZeros(int temp) {
        // TODO Auto-generated method stub
        if (temp <= 0) {
            return "00";
        }
        if (temp < 10) {
            return "0" + temp;
        }
        return temp + "";
    }

    /**
     * 生成一个15位的随机数订单号
     *
     * @return
     */
    public static String creatRequestId() {
        // TODO Auto-generated method stub
        String id = System.currentTimeMillis() + "";
        if (id.equals("") || id.length() < 12)
            id = "88888888888";

        if (id.length() > 15) {
            id = id.substring(0, 15);
        } else if (id.length() < 15) {
            int tmep = 15 - id.length();
            id = id + getRandomCodeStr(tmep);
        }
        return id;
    }


    /**
     * 随机四位
     *
     * @param length
     * @return
     */
    public static String getRandomCodeStr(Integer length) {
        Set<Integer> set = getRandomNumber(length);
        // 使用迭代器
        Iterator<Integer> iterator = set.iterator();
        // 临时记录数据
        String temp = "";
        while (iterator.hasNext()) {
            temp += iterator.next();
        }
        return temp;
    }

    /**
     * 获取一个四位随机数，并且四位数不重复
     *
     * @return Set<Integer>
     */
    private static Set<Integer> getRandomNumber(Integer length) {
        // 使用SET以此保证写入的数据不重复
        Set<Integer> set = new HashSet<Integer>();
        // 随机数
        Random random = new Random();

        while (set.size() < length) {
            // nextInt返回一个伪随机数，它是取自此随机数生成器序列的、在 0（包括）
            // 和指定值（不包括）之间均匀分布的 int 值。
            set.add(random.nextInt(10));
        }
        return set;
    }


    /**
     * 获取网络状态
     *
     * @param context
     * @return
     */
    public static boolean getNetConnectState(Context context) {
        boolean netConnect = false;
        ConnectivityManager connMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        NetworkInfo infoM = connMgr
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (info.isConnected() || infoM.isConnected()) {
            netConnect = true;
        }
        return netConnect;
    }


    /**
     * 去零计算
     *
     * @param temp1
     * @return
     */
    public static String stringProcessing(String temp1) {
        // TODO Auto-generated method stub
        if (temp1.trim().equals("") || temp1.trim().equals("0.0")
                || Double.parseDouble(temp1.trim()) == 0) {
            return "0.00";
        } else {
            double amountCount;
            try {
                amountCount = Double.parseDouble(temp1);
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
                amountCount = 0;
            }
            String temp = new java.text.DecimalFormat(".00")
                    .format(amountCount);
            if (temp.equals("0") || temp.equals("0.0") || temp.equals("0.00")
                    || temp.equals(".00") || temp.equals(".0")) {
                temp = "";
            }
            if (temp.indexOf(".") == 0) {
                temp = temp.replace(".", "0.");
            }
            return temp;
        }
    }

    public static double add(double d1, double d2) {
        BigDecimal b1 = new BigDecimal(Double.toString(d1));
        BigDecimal b2 = new BigDecimal(Double.toString(d2));
        return b1.add(b2).doubleValue();

    }

    public static double sub(double d1, double d2) {
        BigDecimal b1 = new BigDecimal(Double.toString(d1));
        BigDecimal b2 = new BigDecimal(Double.toString(d2));
        return b1.subtract(b2).doubleValue();

    }

    public static double mul(double d1, double d2) {
        BigDecimal b1 = new BigDecimal(Double.toString(d1));
        BigDecimal b2 = new BigDecimal(Double.toString(d2));
        return b1.multiply(b2).doubleValue();

    }

    private static final int DEF_DIV_SCALE = 10;

    public static double div(double d1, double d2) {

        return div(d1, d2, DEF_DIV_SCALE);

    }

    public static double div(double d1, double d2, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }
        BigDecimal b1 = new BigDecimal(Double.toString(d1));
        BigDecimal b2 = new BigDecimal(Double.toString(d2));
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();

    }

    // 任意进制数转为十进制数
    public static String toD(String a, int b) {
        int r = 0;
        for (int i = 0; i < a.length(); i++) {
            r = (int) (r + formatting(a.substring(i, i + 1))
                    * Math.pow(b, a.length() - i - 1));
        }
        return String.valueOf(r);
    }

    public static byte[] int2Bytes(int num) {
        byte[] byteNum = new byte[4];
        for (int ix = 0; ix < 4; ++ix) {
            int offset = 32 - (ix + 1) * 8;
            byteNum[ix] = (byte) ((num >> offset) & 0xff);
        }
        return byteNum;
    }

    // 将十六进制中的字母转为对应的数字
    public static int formatting(String a) {
        int i = 0;
        for (int u = 0; u < 10; u++) {
            if (a.equals(String.valueOf(u))) {
                i = u;
            }
        }
        if (a.equals("a")) {
            i = 10;
        }
        if (a.equals("b")) {
            i = 11;
        }
        if (a.equals("c")) {
            i = 12;
        }
        if (a.equals("d")) {
            i = 13;
        }
        if (a.equals("e")) {
            i = 14;
        }
        if (a.equals("f")) {
            i = 15;
        }
        return i;
    }

    /**
     * 根据生日获取年龄
     *
     * @param birthday
     * @return
     */
    public static int getAgeByBirthday(Date birthday) {
        Calendar cal = Calendar.getInstance();

        if (cal.before(birthday)) {
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }

        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH) + 1;
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);

        cal.setTime(birthday);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH) + 1;
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                // monthNow==monthBirth
                if (dayOfMonthNow < dayOfMonthBirth) {
                    age--;
                }
            } else {
                // monthNow>monthBirth
                age--;
            }
        }
        return age;
    }

    /**
     * 时间戳转换成日期格式字符串
     *
     * @param seconds 精确到秒的字符串
     * @return
     */
    public static String timeStamp2Date(String seconds, String format) {
        if (seconds == null || seconds.isEmpty() || seconds.equals("null")) {
            return "";
        }
        if (format == null || format.isEmpty()) format = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
        return sdf.format(new Date(Long.valueOf(seconds)));
    }

    /**
     * 时间戳转换成日期格式字符串
     *
     * @param seconds 精确到秒的字符串
     * @return
     */
    public static String timeStampDate(String seconds, String format) {
        if (seconds == null || seconds.isEmpty() || seconds.equals("null")) {
            return "";
        }
        if (format == null || format.isEmpty()) format = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(seconds)));
    }

    /**
     * 获取map中第一个数据值
     *
     * @param <K> Key的类型
     * @param <V> Value的类型
     * @param map 数据源
     * @return 返回的值
     */
    public static <K, V> V getFirstOrNull(Map<K, V> map) {
        V obj = null;
        for (Map.Entry<K, V> entry : map.entrySet()) {
            obj = entry.getValue();
            if (obj != null) {
                break;
            }
        }
        return obj;
    }

    public static String getFirstUrlFromHtml(String txt) {

        Document document = Jsoup.parse(txt);
        Elements images = document.select("a[" + "" + "href]");
        String firstImg = "";
        for (Element ele : images) {
            firstImg = Apis.DOWNLOAD_URL + ele.attr("href");
            break;
        }
        return firstImg;
    }

    //根据时间排序
    public static Date stringToDate(String dateString) {
        ParsePosition position = new ParsePosition(0);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date dateValue = simpleDateFormat.parse(dateString, position);
        return dateValue;
    }

    /**
     * 获取当前日期是星期几<br>
     *
     * @param dt
     * @return 当前日期是星期几
     */
    public static String getWeekOfDate(Date dt) {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);

        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;

        return weekDays[w];
    }

    /**
     * 判断一个Activity是否处于栈顶
     *
     * @param mContext
     * @param ClassName 传一个类《class类名》
     * @return
     */
    public static boolean isInLauncher(Context mContext, Class<?> ClassName) {
        ActivityManager manager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        String name = manager.getRunningTasks(1).get(0).topActivity.getClassName();
        if (name.equals(ClassName.getName())) {
            return true;
        }
        return false;
    }

    public static void showNotHasFountDeviced(final Context context) {
        final DialogFactory dialog = new DialogFactory(context);
        dialog.setTitle("提示");
        dialog.setMsg("没有发现设备，为了得到更好的医生服务，请购买设备！");
        dialog.setButtonText(R.id.btn_left, "购买");
        dialog.setButtonText(R.id.btn_middle, "取消");
        dialog.setButtonOnClickListener(R.id.btn_left, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityUtils.showActivity(context, MyShopStoreActivity.class);
                dialog.dismiss();
            }
        });
        dialog.setButtonOnClickListener(R.id.btn_middle, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        if (!dialog.isShowing()) {
            dialog.show();
        }
    }

    /******************/
    public static void setListAnimation(ListView lv) {
        // 为List设置动画效果()
        AnimationSet set = new AnimationSet(true);
        Animation animation = new AlphaAnimation(0.0f, 1.0f);
        animation.setDuration(200);
        set.addAnimation(animation);
        animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        animation.setDuration(150);
        set.addAnimation(animation);
        LayoutAnimationController controller = new LayoutAnimationController(
                set, 0.5f);
        lv.setLayoutAnimation(controller);
    }

    /**
     * 检测是否已注册
     */
    public static boolean isLogin() {
        String username = PreferenceHelper.getString(PreferenceHelper.USERNAME, "");
        if (!TextUtils.isEmpty(username)) {
            //TODO 测试账号只有3位
            boolean isLogin = PreferenceHelper.getBoolean(PreferenceHelper.ISLOGIN, true);
            if (isLogin) {
                return isLogin;
            } else {
                return isLogin;
            }
        } else {
            return false;
        }
    }

    /**
     * 获取版本号
     *
     * @param context
     * @return
     */
    public static int getVersionCode(Context context) {
        int versionCode = 1;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo info = pm.getPackageInfo("com.nf.health.app", PackageManager.GET_CONFIGURATIONS);
            versionCode = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 获取版本名
     *
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        String versionName = "";
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo info = pm.getPackageInfo("com.nf.health.app", PackageManager.GET_CONFIGURATIONS);
            versionName = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }

    /**
     * 检测手机是否有蓝牙模块,是否是支持4.3以上的BLE
     *
     * @return
     */
    public static boolean checkBluetoothAvailable() {
        // 检查当前手机是否支持blue 蓝牙,如果不支持退出程序
        if (!MyApplication.getInstance().getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            return false;
        }
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            return false;
        }
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
            return false;
        } else {
            return true;
        }
    }

    public static void settranslucentStatusBar(Activity cnt) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = cnt.getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            cnt.getWindow().setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = cnt.getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
    }

    /**
     * 根据 1 男 2 女 返回
     * @param sex
     * @return
     */
    public static String getSex(String sex) {
       if (TextUtils.isEmpty(sex)){
           return "未知";
       }else{
           if ("1".equals(sex)){
               return "男";
           }else if ("2".equals(sex)){
               return "女";
           }else{
               return "未知";
           }
       }
    }

    /**
     * 根据 1 男 2 女 返回
     * 高血压/血糖防控计划需要对 ""进行处理，所以新建此方法 不能返回未知
     * @param sex
     * @return
     */
    public static String getSexEmpty(String sex) {
        if (TextUtils.isEmpty(sex)){
            return "";
        }else{
            if ("1".equals(sex)){
                return "男";
            }else if ("2".equals(sex)){
                return "女";
            }else{
                return "";
            }
        }
    }

    /**
     * 获得用户名字,realname 为第一选择
     *
     * @return
     */
    public static String getNameOrNick() {
        String nick = PreferenceHelper.getString(PreferenceHelper.USERNICK, "");
        String name = PreferenceHelper.getString(PreferenceHelper.USERRNAME, "");
        if (!TextUtils.isEmpty(name)) {
            return name;
        } else {
            return nick;
        }
    }
}
